import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'verification_page.dart';
import 'settings_page.dart';
import 'vehicle_info_page.dart';
import 'insurance_page.dart';
import 'help_center_page.dart';
import 'guide_page.dart';
import 'wallet_page.dart';
import 'earnings_page.dart';
import 'rating_page.dart';
import 'service_area_page.dart';
import 'service_time_page.dart';
import 'profile_info_page.dart';
import 'income_stats_page.dart';

/// 个人中心页面
class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  String _phone = '';
  bool _isVerified = false;
  
  @override
  void initState() {
    super.initState();
    _loadUserInfo();
  }

  /// 加载用户信息
  Future<void> _loadUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    final phone = prefs.getString('phone') ?? '';
    final isVerified = prefs.getBool('isVerified') ?? false;
    
    if (mounted) {
      setState(() {
        _phone = phone;
        _isVerified = isVerified;
      });
    }
  }

  /// 切换认证状态（仅用于测试）
  Future<void> _toggleVerificationStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final newStatus = !_isVerified;
    await prefs.setBool('isVerified', newStatus);
    
    setState(() {
      _isVerified = newStatus;
    });
  }

  /// 构建头部信息
  Widget _buildHeader() {
    // 格式化手机号 138****8888
    final maskedPhone = _phone.isNotEmpty 
        ? '${_phone.substring(0, 3)}****${_phone.substring(7)}'
        : 'Unknown';

    return Container(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 16),  // 减小内边距
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(16),
          bottomRight: Radius.circular(16),
        ),
      ),
      child: Column(
        children: [
          InkWell(  // 添加点击效果
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const ProfileInfoPage(),
                ),
              );
            },
            child: Row(
              children: [
                Container(
                  width: 56,  // 减小头像尺寸
                  height: 56,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: const Color(0xFFFF5722),
                      width: 2,
                    ),
                    image: const DecorationImage(
                      image: NetworkImage('https://picsum.photos/64'),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                const SizedBox(width: 12),  // 减小间距
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            maskedPhone,
                            style: const TextStyle(
                              fontSize: 18,  // 减小字号
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,  // 减小内边距
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: const Color(0xFFFF5722).withOpacity(0.1),
                              borderRadius: BorderRadius.circular(20),
                              border: Border.all(
                                color: const Color(0xFFFF5722),
                                width: 1,
                              ),
                            ),
                            child: const Text(
                              '专业搬家师傅',
                              style: TextStyle(
                                fontSize: 11,  // 减小字号
                                color: Color(0xFFFF5722),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),  // 减小间距
                      Text(
                        '工号：SF${_phone.substring(5)}',
                        style: TextStyle(
                          fontSize: 12,  // 减小字号
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const ProfileInfoPage(),
                      ),
                    );
                  },
                  icon: const Icon(Icons.chevron_right),
                  color: Colors.grey[400],
                  padding: EdgeInsets.zero,  // 移除图标内边距
                  constraints: const BoxConstraints(),  // 移除图标约束
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),  // 减小间距
          Container(
            padding: const EdgeInsets.all(12),  // 减小内边距
            decoration: BoxDecoration(
              color: const Color(0xFFFAFAFA),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: const Color(0xFFEEEEEE),
              ),
            ),
            child: Row(
              children: [
                Expanded(
                  child: Column(
                    children: [
                      Text(
                        '4.9',
                        style: TextStyle(
                          fontSize: 18,  // 减小字号
                          fontWeight: FontWeight.w600,
                          color: Colors.grey[800],
                        ),
                      ),
                      const SizedBox(height: 2),  // 减小间距
                      Text(
                        '服务评分',
                        style: TextStyle(
                          fontSize: 11,  // 减小字号
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 1,
                  height: 20,  // 减小分隔线高度
                  color: const Color(0xFFEEEEEE),
                ),
                Expanded(
                  child: Column(
                    children: [
                      Text(
                        '268',
                        style: TextStyle(
                          fontSize: 18,  // 减小字号
                          fontWeight: FontWeight.w600,
                          color: Colors.grey[800],
                        ),
                      ),
                      const SizedBox(height: 2),  // 减小间距
                      Text(
                        '服务订单',
                        style: TextStyle(
                          fontSize: 11,  // 减小字号
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 1,
                  height: 20,  // 减小分隔线高度
                  color: const Color(0xFFEEEEEE),
                ),
                Expanded(
                  child: Column(
                    children: [
                      Text(
                        '98%',
                        style: TextStyle(
                          fontSize: 18,  // 减小字号
                          fontWeight: FontWeight.w600,
                          color: Colors.grey[800],
                        ),
                      ),
                      const SizedBox(height: 2),  // 减小间距
                      Text(
                        '好评率',
                        style: TextStyle(
                          fontSize: 11,  // 减小字号
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建未认证状态的头部
  Widget _buildUnverifiedHeader(BuildContext context) {
    return Container(
      margin: const EdgeInsets.fromLTRB(12, 0, 12, 0),  // 修改边距
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(  // 改为 Row
        children: [
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: Colors.grey[100],
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.person_outline,
              size: 24,
              color: Colors.grey[400],
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _phone.isNotEmpty 
                      ? '${_phone.substring(0, 3)}****${_phone.substring(7)}'
                      : '未登录',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 4),
                const Text(
                  '请完成实名认证',
                  style: TextStyle(
                    fontSize: 13,
                    color: Color(0xFFFF5722),
                  ),
                ),
              ],
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const VerificationPage(),
                ),
              );
            },
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFFFF5722),
              padding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 6,
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: const BorderSide(
                  color: Color(0xFFFF5722),
                ),
              ),
            ),
            child: const Text('去认证'),
          ),
        ],
      ),
    );
  }

  /// 构建菜单项
  Widget _buildMenuItem({
    required String title,
    required IconData icon,
    String? subtitle,
    VoidCallback? onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),  // 调整内边距
        child: Row(
          children: [
            Icon(
              icon,
              size: 20,
              color: Colors.grey[700],
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                title,
                style: const TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            Icon(
              Icons.chevron_right,
              size: 20,
              color: Colors.grey[400],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建菜单分组
  Widget _buildMenuGroup(List<Widget> children) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: children.map((child) => child).toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        title: const Text(
          '我的',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w500,
          ),
        ),
        actions: [
          // 添加测试按钮（仅用于开发）
          IconButton(
            onPressed: _toggleVerificationStatus,
            icon: Icon(
              _isVerified ? Icons.verified_user : Icons.verified_user_outlined,
              color: _isVerified ? const Color(0xFFFF5722) : Colors.grey,
            ),
          ),
          IconButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const SettingsPage(),
                ),
              );
            },
            icon: const Icon(Icons.settings_outlined),
            color: Colors.grey[700],
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 根据认证状态显示不同的头部
            _isVerified ? _buildHeader() : _buildUnverifiedHeader(context),
            const SizedBox(height: 12),
            // 未认证状态显示认证指南
            if (!_isVerified) ...[
              _buildMenuGroup([
                _buildMenuItem(
                  title: '认证指南',
                  icon: Icons.assignment_outlined,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const GuidePage(),
                      ),
                    );
                  },
                ),
                _buildMenuItem(
                  title: '常见问题',
                  icon: Icons.help_outline,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const HelpCenterPage(),
                      ),
                    );
                  },
                ),
              ]),
            ] else ...[
              // 已认证状态显示功能菜单
              _buildMenuGroup([
                _buildMenuItem(
                  title: '我的钱包',
                  icon: Icons.account_balance_wallet_outlined,
                  subtitle: '¥1,234.56',
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const WalletPage(),
                      ),
                    );
                  },
                ),
                _buildMenuItem(
                  title: '收益统计',
                  icon: Icons.bar_chart,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const IncomeStatsPage(),
                      ),
                    );
                  },
                ),
              ]),
              const SizedBox(height: 12),
              _buildMenuGroup([
                _buildMenuItem(
                  title: '服务评价',
                  icon: Icons.star_outline,
                  subtitle: '4.9分',
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const RatingPage(),
                      ),
                    );
                  },
                ),
                _buildMenuItem(
                  title: '服务区域',
                  icon: Icons.location_on_outlined,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const ServiceAreaPage(),
                      ),
                    );
                  },
                ),
                _buildMenuItem(
                  title: '服务时间',
                  icon: Icons.access_time,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const ServiceTimePage(),
                      ),
                    );
                  },
                ),
              ]),
              const SizedBox(height: 12),
              _buildMenuGroup([
                _buildMenuItem(
                  title: '车辆信息',
                  icon: Icons.local_shipping_outlined,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const VehicleInfoPage(),
                      ),
                    );
                  },
                ),
                _buildMenuItem(
                  title: '保险服务',
                  icon: Icons.security_outlined,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const InsurancePage(),
                      ),
                    );
                  },
                ),
                _buildMenuItem(
                  title: '帮助中心',
                  icon: Icons.help_outline,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const HelpCenterPage(),
                      ),
                    );
                  },
                ),
              ]),
            ],
            // 添加底部边距
            const SizedBox(height: 24),
          ],
        ),
      ),
    );
  }
} 